import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface LogEntry {
  id: string
  timestamp: string
  level: 'INFO' | 'WARNING' | 'ERROR' | 'CRITICAL' | 'DEBUG'
  source: string
  message: string
  rawLine: string
  lineNumber: number
}

export interface LogFile {
  path: string
  name: string
  size: string
  lastModified: string
  isDirectory: boolean
  children?: LogFile[]
}

export interface LogFilter {
  keyword: string
  level: string[]
  timeRange: [number, number] | null
  source: string
}

export const useLogTrackerStore = defineStore('logTracker', () => {
  // 状态
  const logs = ref<LogEntry[]>([])
  const isTracking = ref(false)
  const isPaused = ref(false)
  const currentFile = ref<string | null>(null)
  const filter = ref<LogFilter>({
    keyword: '',
    level: [],
    timeRange: null,
    source: ''
  })
  const maxLogEntries = ref(1000) // 最大日志条数
  const autoScroll = ref(true)
  const highlightKeywords = ref(['ERROR', 'WARNING', 'CRITICAL', 'FAIL', 'EXCEPTION'])
  
  // 模拟数据
  let logSimulationInterval: NodeJS.Timeout | null = null
  let logIdCounter = 0

  // 计算属性
  const filteredLogs = computed(() => {
    let result = logs.value

    // 关键字过滤
    if (filter.value.keyword) {
      const keyword = filter.value.keyword.toLowerCase()
      result = result.filter(log => 
        log.message.toLowerCase().includes(keyword) ||
        log.source.toLowerCase().includes(keyword)
      )
    }

    // 级别过滤
    if (filter.value.level.length > 0) {
      result = result.filter(log => filter.value.level.includes(log.level))
    }

    // 时间范围过滤
    if (filter.value.timeRange) {
      const [start, end] = filter.value.timeRange
      result = result.filter(log => {
        const logTime = new Date(log.timestamp).getTime()
        return logTime >= start && logTime <= end
      })
    }

    // 来源过滤
    if (filter.value.source) {
      const source = filter.value.source.toLowerCase()
      result = result.filter(log => log.source.toLowerCase().includes(source))
    }

    return result
  })

  const logStats = computed(() => {
    const stats = {
      total: logs.value.length,
      info: 0,
      warning: 0,
      error: 0,
      critical: 0,
      debug: 0
    }

    logs.value.forEach(log => {
      switch (log.level) {
        case 'INFO': stats.info++; break
        case 'WARNING': stats.warning++; break
        case 'ERROR': stats.error++; break
        case 'CRITICAL': stats.critical++; break
        case 'DEBUG': stats.debug++; break
      }
    })

    return stats
  })

  // 方法
  const startTracking = (filePath: string) => {
    if (isTracking.value) {
      stopTracking()
    }

    currentFile.value = filePath
    isTracking.value = true
    isPaused.value = false
    logs.value = []

    // 模拟实时日志追踪
    startLogSimulation()
  }

  const stopTracking = () => {
    isTracking.value = false
    isPaused.value = false
    currentFile.value = null
    
    if (logSimulationInterval) {
      clearInterval(logSimulationInterval)
      logSimulationInterval = null
    }
  }

  const pauseTracking = () => {
    isPaused.value = true
    if (logSimulationInterval) {
      clearInterval(logSimulationInterval)
      logSimulationInterval = null
    }
  }

  const resumeTracking = () => {
    if (isTracking.value && isPaused.value) {
      isPaused.value = false
      startLogSimulation()
    }
  }

  const clearLogs = () => {
    logs.value = []
    logIdCounter = 0
  }

  const addLogEntry = (entry: Omit<LogEntry, 'id'>) => {
    const newEntry: LogEntry = {
      ...entry,
      id: `log_${++logIdCounter}`
    }

    logs.value.push(newEntry)

    // 限制日志条数
    if (logs.value.length > maxLogEntries.value) {
      logs.value = logs.value.slice(-maxLogEntries.value)
    }
  }

  const updateFilter = (newFilter: Partial<LogFilter>) => {
    filter.value = { ...filter.value, ...newFilter }
  }

  const exportLogs = (format: 'txt' | 'json' = 'txt') => {
    const logsToExport = filteredLogs.value
    
    if (format === 'json') {
      return JSON.stringify(logsToExport, null, 2)
    } else {
      return logsToExport.map(log => 
        `[${log.timestamp}] [${log.level}] [${log.source}] ${log.message}`
      ).join('\n')
    }
  }

  const downloadLogs = (filename?: string, format: 'txt' | 'json' = 'txt') => {
    const content = exportLogs(format)
    const blob = new Blob([content], { type: format === 'json' ? 'application/json' : 'text/plain' })
    const url = URL.createObjectURL(blob)
    
    const a = document.createElement('a')
    a.href = url
    a.download = filename || `logs_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.${format}`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  // 模拟日志生成
  const startLogSimulation = () => {
    if (logSimulationInterval) {
      clearInterval(logSimulationInterval)
    }

    logSimulationInterval = setInterval(() => {
      if (!isPaused.value && isTracking.value) {
        generateMockLogEntry()
      }
    }, 1000 + Math.random() * 3000) // 1-4秒随机间隔
  }

  const generateMockLogEntry = () => {
    const levels: LogEntry['level'][] = ['INFO', 'WARNING', 'ERROR', 'CRITICAL', 'DEBUG']
    const sources = ['kernel', 'systemd', 'sshd', 'cron', 'NetworkManager', 'bmc-server']
    const messages = [
      'System startup completed successfully',
      'CPU temperature high: 85°C',
      'Power supply 1 failed!',
      'Memory test passed',
      'Network interface eth0 up',
      'User login successful',
      'Disk space warning: /var 90% full',
      'Service restart required',
      'Configuration file updated',
      'Hardware sensor error detected',
      'Backup process completed',
      'Security scan finished'
    ]

    const level = levels[Math.floor(Math.random() * levels.length)]
    const source = sources[Math.floor(Math.random() * sources.length)]
    const message = messages[Math.floor(Math.random() * messages.length)]
    const timestamp = new Date().toISOString()
    const lineNumber = logs.value.length + 1

    addLogEntry({
      timestamp,
      level,
      source,
      message,
      rawLine: `${timestamp} ${source}: ${message}`,
      lineNumber
    })
  }

  // 高亮处理
  const highlightLogMessage = (message: string): string => {
    let highlighted = message
    
    highlightKeywords.value.forEach(keyword => {
      const regex = new RegExp(`(${keyword})`, 'gi')
      highlighted = highlighted.replace(regex, '<span class="log-highlight log-highlight-$1">$1</span>')
    })

    return highlighted
  }

  const getLevelColor = (level: LogEntry['level']): string => {
    switch (level) {
      case 'ERROR': return '#ff4d4f'
      case 'WARNING': return '#faad14'
      case 'CRITICAL': return '#a0d911'
      case 'INFO': return '#1890ff'
      case 'DEBUG': return '#722ed1'
      default: return '#d9d9d9'
    }
  }

  return {
    // 状态
    logs,
    isTracking,
    isPaused,
    currentFile,
    filter,
    maxLogEntries,
    autoScroll,
    highlightKeywords,
    
    // 计算属性
    filteredLogs,
    logStats,
    
    // 方法
    startTracking,
    stopTracking,
    pauseTracking,
    resumeTracking,
    clearLogs,
    addLogEntry,
    updateFilter,
    exportLogs,
    downloadLogs,
    highlightLogMessage,
    getLevelColor
  }
})